//
//  LBFacCollectionViewFlowLayout.m
//  LBFacListView
//
//  Created by luckyRoy on 2017/10/23.
//

#import "LBFacCustomCollectionViewFlowLayout.h"

@interface LBFacCustomCollectionViewFlowLayout ()<UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)NSMutableArray *framesArray;
@property(nonatomic,assign)CGFloat contentHeight;
@property(nonatomic,assign)CGFloat rowHeight;///< 固定行高
@property (nonatomic, strong) NSMutableArray *attributesArray;
@property (nonatomic, assign) BOOL isNeedRefresh;
@end

@implementation LBFacCustomCollectionViewFlowLayout

#pragma mark - 初始化属性
- (instancetype)init {
    self = [super init];
    if (self) {
        _framesArray = [NSMutableArray array];
    }
    return self;
}

#pragma mark - 重写父类的方法，实现瀑布流布局
//step1
- (void)prepareLayout {
    [super prepareLayout];
    [self calculateFrames];
}

#pragma mark - CollectionView的滚动范围
//step2
- (CGSize)collectionViewContentSize
{
    CGFloat width = self.collectionView.frame.size.width;
    return CGSizeMake(width, _contentHeight);
}

#pragma mark - 当尺寸有所变化时，重新刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

#pragma mark - 所有cell和view的布局属性
//sectionheader sectionfooter decorationview collectionviewcell的属性都会走这个方法
//step3
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    [self.attributesArray removeAllObjects];
    
    CGFloat maxY = 0;
    
    for(NSInteger section = 0; section < _framesArray.count; section++){
        NSArray *currentSectionFrames = _framesArray[section];
        
        if (!currentSectionFrames.count) {
            if (section >= 0) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
                UICollectionViewLayoutAttributes *headerAttr = [[self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                                     atIndexPath:indexPath] copy];
                CGRect frame = headerAttr.frame;
                frame.origin.y = maxY;
                headerAttr.frame = frame;
                if (headerAttr) {
                    [self.attributesArray addObject:headerAttr];
                }
                maxY = CGRectGetMaxY(frame);
            }
        }
        for(NSInteger row = 0; row < currentSectionFrames.count; row++){
            CGRect currentFrame = [currentSectionFrames[row] CGRectValue];
            NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
                //first section header should show
            if(row == 0){
                UICollectionViewLayoutAttributes *headerAttr = [[self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                                     atIndexPath:currentIndexPath] copy];
                CGRect frame = headerAttr.frame;
                frame.origin.y = maxY;
                headerAttr.frame = frame;
                if (headerAttr) {
                    [self.attributesArray addObject:headerAttr];
                }
                maxY = CGRectGetMaxY(frame);
            }
                
                //cell should show
                UICollectionViewLayoutAttributes *cellAttrs = [[self layoutAttributesForItemAtIndexPath:currentIndexPath] copy];
                cellAttrs.frame = currentFrame;
                if (cellAttrs) {
                    [self.attributesArray addObject:cellAttrs];
                }
                maxY = CGRectGetMaxY(currentFrame);
        }
    }
    return self.attributesArray;
}

- (BOOL)isCellModelFrameNeedChange
{
    BOOL isChange = NO;
    
    NSInteger sectionCount = self.collectionView.numberOfSections;
    
    for(NSInteger section = 0; section < sectionCount; section++) {
        if (section < _framesArray.count) {
            NSInteger numberOfRows = [self.collectionView numberOfItemsInSection:section];
            NSMutableArray *currentSectionFrames = _framesArray[section];
            if (numberOfRows != currentSectionFrames.count) {
                isChange = YES;
                break;
            }
        }
        
    }
    
    return isChange;
}

#pragma mark---other methods
- (void)calculateFrames
{
    self.isNeedRefresh = [self isCellModelFrameNeedChange];
    if (_framesArray.count && !self.isNeedRefresh) {
        return;
    }
    [_framesArray removeAllObjects];
    
    CGFloat maxY = 0;
    
    NSInteger sectionCount = self.collectionView.numberOfSections;
    for(NSInteger section = 0; section < sectionCount; section++){
        NSMutableArray *currentSectionFrames = [NSMutableArray arrayWithCapacity:sectionCount];
        [_framesArray addObject:currentSectionFrames];
        
        NSInteger numberOfRows = [self.collectionView numberOfItemsInSection:section];
        
        if (!numberOfRows) {
            
            self.headerReferenceSize = [self.fac_delegate collectionView:self.collectionView layout:self referenceSizeForHeaderInSection:section];
            
            maxY += self.headerReferenceSize.height;
        }
        
        for(NSInteger row = 0; row < numberOfRows; row++){
            NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:row inSection:section];

            self.headerReferenceSize = [self.fac_delegate collectionView:self.collectionView layout:self referenceSizeForHeaderInSection:section];
            self.rowHeight = [self.fac_delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:currentIndexPath].height;
            
            CGFloat x = self.sectionInset.left;
            //如果有sectionheader需要加上sectionheader高度
            CGFloat y = 0;
            
            if (0 == row) {
                y = (self.headerReferenceSize.height + maxY);
            } else {
                CGRect lastCellFrame = [[currentSectionFrames lastObject] CGRectValue];
                y = lastCellFrame.origin.y;
            }
            
            //判断获得前一个cell的frame
            NSInteger preRow = row - 1;
            if(preRow >= 0 && currentSectionFrames.count > preRow){
                CGRect preCellFrame = [currentSectionFrames[preRow] CGRectValue];
                x = preCellFrame.origin.x + preCellFrame.size.width + self.minimumInteritemSpacing;
            }
            
            CGFloat currentWidth = [self.fac_delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:currentIndexPath].width;
            //保证一个cell不超过最大宽度
            currentWidth = MIN(currentWidth, self.collectionView.frame.size.width - self.sectionInset.left - self.sectionInset.right);
            if(x + currentWidth > self.collectionView.frame.size.width - self.sectionInset.right){
                //超出范围，换行
                x = self.sectionInset.left;
                y += _rowHeight + self.minimumLineSpacing;
            }
            // 创建属性
            CGRect currentCellFrame = CGRectMake(x, y, currentWidth, _rowHeight);
            
            maxY = CGRectGetMaxY(currentCellFrame);
            
            [currentSectionFrames addObject:[NSValue valueWithCGRect:currentCellFrame]];
        }
    }
    _contentHeight = maxY;
}

- (NSMutableArray *)attributesArray
{
    if (!_attributesArray) {
        _attributesArray = [[NSMutableArray alloc]init];
    }
    return _attributesArray;
}

@end
